//
//  LRComposeViewController.swift
//  LRWeibo
//
//  Created by 雷路荣 on 15/12/26.
//  Copyright © 2015年 leilurong. All rights reserved.
//

import UIKit
import SVProgressHUD
enum LRComposeViewControllerType: Int {
    case Compose = 1 //发微博
    case Repost = 2 //转发
    case Comment = 3 //评论
}

class LRComposeViewController: UIViewController {

    /// 微博模型
    var status: LRStatues?
    
    /// toolBar底部约束
    private var toolBarBottomConstraint: NSLayoutConstraint?
    
    /// 微博最大的长度
    private let maxTipLength = 18
    
    /// 照片选择器的view的底部约束
    private var photoSelectorViewBottomConstraint: NSLayoutConstraint?
    
    /// 控制器类型
    private var controllerType: LRComposeViewControllerType
    
    init(controllerType:LRComposeViewControllerType){
        self.controllerType = controllerType
        super.init(nibName: nil, bundle: nil)
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //控制器销毁调用
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    // 在用户看得到界面的时候来弹出键盘.
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        // 照片选择器没有出现的时候,就弹出键盘
        if photoSelectorViewBottomConstraint?.constant != 0 {
            // 说明照片选择器的view看不到
            // 弹出键盘
            textView.becomeFirstResponder()
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 将照片选择控制器管理起来,不然他modal出控制器后,自己会跑了
        // 只有管理起来的控制器才能接受到一些系统事件,例如屏幕的旋转
        self.addChildViewController(photoSelectorVc)
        self.addChildViewController(emoticonVc)
        
        // 需要设置背景颜色,不然弹出时动画有问题
        view.backgroundColor = UIColor.whiteColor()
        // 设置导航栏按钮
        setupNavBarButtonItem()
        // 设置导航栏标题
        setupNavAttributedTitle()
        // 设置textView
        setupTextView()
        // 设置照片选择器,层级要在toolBar后面，textView前面
        setupPhotoSelector()
        // 设置toolBar
        setupToolBar()
        // 设置提示文字长度的label
        setupTipLengthLabel()
        // 1通知中心方法监听
//        NSNotificationCenter.defaultCenter().addObserver(self, selector: "textViewTextDidChange", name: UITextViewTextDidChangeNotification, object: nil)
//        //一开始就判断发送按钮是否可用
//        textViewTextDidChange()
        // 监听键盘frame
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        
        // 一开始就显示剩余文字长度
        tipLenghtLabel.text = String(maxTipLength)
        
    }
//    //1 监听回调方法 判断发送按钮是否可用
//    func textViewTextDidChange(){
//        navigationItem.rightBarButtonItem?.enabled = textView.text.characters.count != 0
//    }
    //1 键盘监听回调方法，改变工具条底部约束
    func keyboardWillChangeFrame(notification: NSNotification) {
        //print("notification = \(notification)")
        /* 键盘弹出
            notification = NSConcreteNotification 0x7f874b24e480 {name = UIKeyboardWillChangeFrameNotification; userInfo = {
            UIKeyboardAnimationCurveUserInfoKey = 7;
            UIKeyboardAnimationDurationUserInfoKey = "0.25";//动画时间
            UIKeyboardBoundsUserInfoKey = "NSRect: {{0, 0}, {375, 258}}";//键盘宽高
            UIKeyboardCenterBeginUserInfoKey = "NSPoint: {187.5, 796}";//开始中心
            UIKeyboardCenterEndUserInfoKey = "NSPoint: {187.5, 538}";//结束中心
            UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 667}, {375, 258}}";//开始坐标
            UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 409}, {375, 258}}";//结束坐标
            UIKeyboardIsLocalUserInfoKey = 1;
        }}
        */
        let userInfo = notification.userInfo
        //获取动画时间
        let duration = userInfo![UIKeyboardAnimationDurationUserInfoKey]?.doubleValue
        //获取结束坐标
        let endFrame = userInfo![UIKeyboardFrameEndUserInfoKey]?.CGRectValue
        //获取偏移值 改变底部约束
        toolBarBottomConstraint?.constant = endFrame!.origin.y - view.frame.size.height
        UIView.animateWithDuration(duration!) { () -> Void in
            //布局
            self.view.layoutIfNeeded()
        }
    }

    /// 设置导航栏按钮
    private func setupNavBarButtonItem() {
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "sendStatus")
        self.navigationItem.rightBarButtonItem?.enabled = false
    }
    /// 设置导航栏标题
    private func setupNavAttributedTitle() {
        // 默认发微博
        var prefix = "发微博"
        if controllerType == LRComposeViewControllerType.Repost {
            prefix = "转发微博"
        }else if controllerType == LRComposeViewControllerType.Comment {
            prefix = "评论微博"
        }
        //获取用户名
        if let name = LRUserAccount.loadUserAccount()?.screen_name {
            //标题
            let title = prefix + "\n" + name
            //创建克兵文本属性
            let arrtributeTitle = NSMutableAttributedString(string: title)
            // 创建label
            let label = UILabel()
            label.numberOfLines = 0
            label.textAlignment = NSTextAlignment.Center
            label.font = UIFont.systemFontOfSize(18)
            // 获取NSRange
            let nameRange = (title as NSString).rangeOfString(name)
            // 设置属性文本的属性
            arrtributeTitle.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(14), range: nameRange)
            arrtributeTitle.addAttribute(NSForegroundColorAttributeName, value: UIColor.darkGrayColor(), range: nameRange)
            // 顺序不要搞错
            label.attributedText = arrtributeTitle
            label.sizeToFit()
            navigationItem.titleView = label
        }else {
            // 没有用户名
            navigationItem.title = prefix
        }
    }
    /// 设置textView
    private func setupTextView() {
        //添加子控件
        view.addSubview(textView)
        //设置约束
        textView.ff_Fill(view)
        //添加textView的代理,来监听文字的改变，判断是否启用发送按钮
        textView.delegate = self
    }
    /// 设置toolBar
    private func setupToolBar() {
        view.addSubview(toolBar)
        let constraint = toolBar.ff_AlignInner(type: ff_AlignType.BottomLeft, referView: view, size: CGSizeMake(UIScreen.mainScreen().bounds.width, 44))
        //获取底部约束
        toolBarBottomConstraint = toolBar.ff_Constraint(constraint, attribute: NSLayoutAttribute.Bottom)
         // 每个item对应的图片名称, 数组里面有5个字典 imageName 对应的value就是要显示的图片 action是方法
        let itemSettings = [["imageName": "compose_toolbar_picture", "action": "picture"],
            ["imageName": "compose_mentionbutton_background", "action": "mention"],
            ["imageName": "compose_trendbutton_background", "action": "trend"],
            ["imageName": "compose_emoticonbutton_background", "action": "emoticon"],
            ["imageName": "compose_addbutton_background", "action": "add"]]
        // 创建空数组应用存储工具条上的item
        var items = [UIBarButtonItem]()
        // 记录按钮是第几个,作为按钮的tag
        var index = 0
        // 遍历数组,获取图片的名称
        for dict in itemSettings {
            // 创建UIBarButtonItem
            let item = UIBarButtonItem(imageName: dict["imageName"]!)
            // 给item里面的按钮添加点击事件,item没有方法添加事件，通过customView
            let button = item.customView as! UIButton
//---注意--// action: 如果是字符串,可以直接使用,如果是一个变量或常量,需要使用Selector
            button.addTarget(self, action: Selector(dict["action"]!), forControlEvents: UIControlEvents.TouchUpInside)
            //记录tag
            button.tag = index
//---注意--// 不要直接toolBar.items.append,因为 toolBar.items 没有值
            //toolBar.items?.append(item)
            //保存到数组
            items.append(item)
            //添加弹簧
            let FlexibleSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
            //保存到数组
            items.append(FlexibleSpace)
            
            index++
        }
        //移除最后一根弹簧
        items.removeLast()
        //将items数组赋值给工具条
        toolBar.items = items
    }
    /// 设置提示文字长度的label
    private func setupTipLengthLabel() {
        // 1.添加子控件
        view.addSubview(tipLenghtLabel)
        // 2.添加约束
        tipLenghtLabel.ff_AlignVertical(type: ff_AlignType.TopRight, referView: toolBar, size: nil, offset: CGPoint(x: -4, y: -4))
    }
    
    /// 设置照片选择器
    private func setupPhotoSelector() {
        
        let photoSelectorView = photoSelectorVc.view
        view.addSubview(photoSelectorView)
        
        photoSelectorView.translatesAutoresizingMaskIntoConstraints = false
        // 水平填充父控件
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[psv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["psv" : photoSelectorView]))
        
        // 垂直方向,高度是父控件的60%
        view.addConstraint(NSLayoutConstraint(item: photoSelectorView, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: view.frame.height * 0.6))
        
        // 底部和父控件底部重合，再往下移动照片选择器的高度
        photoSelectorViewBottomConstraint = NSLayoutConstraint(item: photoSelectorView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: view.frame.height * 0.6)
        view.addConstraint(photoSelectorViewBottomConstraint!)
    }
        
    
    // MARK: - toolBar点击事件
    func picture() {
        print("图片")
        // 让照片选择器的view回到上面来
        photoSelectorViewBottomConstraint?.constant = 0
        //键盘退下
        textView.resignFirstResponder()
        //动画
        UIView.animateWithDuration(0.25) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
    
    func trend() {
        print("#")
    }
    
    func mention() {
        print("@")
    }
    
    /*表情按钮点击， 切换键盘
    textView弹出键盘之前:
    1.如果inputView == nil,会弹系统的键盘
    2.如果inputView != nil,弹对应的键盘
    */
    func emoticon() {
        print("textView.inputView: \(textView.inputView)")
        // 将键盘退回,如果退出键盘和弹出键盘事件相差很短,不会有退回去和弹出来的动画
        textView.resignFirstResponder()
        
        // 单位秒NSEC_PER_SEC
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
//        })
        // 延迟0.25在弹出键盘
        // 单位毫秒USEC_PER_SEC
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(250 * USEC_PER_SEC)), dispatch_get_main_queue()) { () -> Void in
            // 如果使用的是系统键盘,就切换到我们的键盘,如果使用的是我们的键盘就切换到系统
            self.textView.inputView = self.textView.inputView == nil ?  self.emoticonVc.view : nil
            // 再次弹出键盘
            self.textView.becomeFirstResponder()
        }
    }
    
    func add() {
        print("加号")
    }
    

    //MARK: - 取消
    func close() {
        self.textView.resignFirstResponder()
        SVProgressHUD.dismiss()
        self.dismissViewControllerAnimated(true, completion: nil)
    }
    //MARK: - 发送按钮点击
    func sendStatus() {
        // 获取textView的文本内容发送给服务器
        let text = textView.emoticonText()
        
        // 获取照片选择器的图片，获取第一张,新浪值允许第三方显示一张
        let image = photoSelectorVc.photoes.first
        
        // 如果微博内容超出长度,提示用户
        if maxTipLength - text.characters.count < 0 {
            SVProgressHUD.showErrorWithStatus("微博内容超出长度")
            return
        }
        //关闭键盘
        textView.endEditing(true)
        if controllerType == LRComposeViewControllerType.Compose {
            //显示正在发送
            SVProgressHUD.showWithStatus("正在发布微博！", maskType: SVProgressHUDMaskType.Black)
            //发布微博
            LRNetworkTool.sharedNetworkTool.sendStatus(text, image: image, finished: { (result, error) -> () in
                if error != nil {
                    SVProgressHUD.showErrorWithStatus("网络不给力", maskType: SVProgressHUDMaskType.Black)
                    return
                }
                print("发布微博成功:\(result)")
                SVProgressHUD.showSuccessWithStatus("发送微博成功!")
                // 发送成功, 直接关闭指示器和界面
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                    self.close()
                })
            })
        }else if controllerType == LRComposeViewControllerType.Repost {
            //提示正在转发
            SVProgressHUD.showWithStatus("正在转发微博...", maskType: SVProgressHUDMaskType.Black)
            //转发微博
            LRNetworkTool.sharedNetworkTool.repostStatus((status?.id)!, status: text, finished: { (result, error) -> () in
                if error != nil {
                    SVProgressHUD.showErrorWithStatus("网络不给力！", maskType: SVProgressHUDMaskType.Black)
                    return
                }
                print("转发微博成功:\(result)")
                // 转发成功, 直接关闭界面
                self.close()
            })
        }else if controllerType == LRComposeViewControllerType.Comment {
            //提示正在评论
            SVProgressHUD.showWithStatus("正在评论微博", maskType: SVProgressHUDMaskType.Black)
            //评论微博
            LRNetworkTool.sharedNetworkTool.commentStatus((status?.id)!, comment: text, finished: { (result, error) -> () in
                if error != nil {
                    SVProgressHUD.showErrorWithStatus("网络不给力！", maskType: SVProgressHUDMaskType.Black)
                    return
                }
                print("评论微博成功:\(result)")
                // 转发成功, 直接关闭界面
                self.close()
            })
        }
    }
    
    //MARK: - 懒加载
    /*
        iOS中可以让用户输入的控件
        1.TextField
        1.只能输入一行
        2.有占位文本
        3.继承自UIControl不能滚动
        
        2.TextView
        1.可以输入多行
        2.没有占位文本
        3.继承自scrollView可以滚动
    */
    private lazy var textView: LRPlaceholderTextView = {
        let textView = LRPlaceholderTextView()
        // 当textView被拖动的时候就会将键盘退回,textView能拖动
        textView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        textView.font = UIFont.systemFontOfSize(18)
        textView.backgroundColor = UIColor.brownColor()
        textView.textColor = UIColor.redColor()
        textView.bounces = true
        textView.alwaysBounceVertical = true //垂直方向弹簧效果
        textView.placeholderText = "分享新鲜事..."
        return textView
    }()
    // 工具条
    private lazy var toolBar: UIToolbar = {
        let toolBar = UIToolbar()
        toolBar.backgroundColor = UIColor(white: 0.8, alpha: 1)
        return toolBar
    }()
    /// 剩余文字数量的label
    private lazy var tipLenghtLabel: UILabel = {
        let label = UILabel()
        //设置字体
        label.font = UIFont.systemFontOfSize(24)
        //设置颜色
        label.textColor = UIColor.lightGrayColor()
        return label
    }()
    /// 表情键盘控制器
    private lazy var emoticonVc: LREmoticonController = LREmoticonController(textView: self.textView)
    /// 照片选择控制器
    private lazy var photoSelectorVc: LRPhotoSelectorController = LRPhotoSelectorController()
}
//MARK: - 扩展 遵守UITextViewDelegate ------------------------------------------------------
extension LRComposeViewController: UITextViewDelegate {
    //textView文本发生改变系统就自动调用
    func textViewDidChange(textView: UITextView) {
        //有文本就启用发送按钮
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        // 获取textView现有的文字数量
        let count = textView.emoticonText().characters.count
        // 用最大文字数量 - 现有文字数量
        let length = maxTipLength - count
        // 设置剩余文字数量
        tipLenghtLabel.text = String(length)
        // 如果剩余数量小于0显示红色,否则显示灰色
        tipLenghtLabel.textColor = length < 0 ? UIColor.redColor() : UIColor.lightGrayColor()
    }

}
